# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import traceback
import json
import datetime
import sys
from django.shortcuts import render
from django.http import JsonResponse
from django.db import connection
from django.db.models import Q
from common.requests import err_requests, success_requests, get_body
from models import BorrowRecord, ReturnRecord
from apps.organize_manager.models import CloudAuthUser
from apps.archives_file.models import ArchivesFile
from apps.borrow.dataview.sql.mysql import borrow_sql


def oper_borrow(request):
    """
    借阅资料
    """
    try:
        if request.method != 'POST':
            return err_requests("500", "请求方法错误，请用POST请求")
        body = request.POST
        print 'body: %s' % body
        borrow = BorrowRecord()
        try:
            archive_id = int(body.get('archive_id'))
        except Exception as e:
            traceback.print_exc()
            return err_requests(
                "500", "档案id：%s格式错误" % body.get('archive_id')
            )
        
        archive_query = ArchivesFile.objects.filter(id=archive_id)
        if not archive_query:
            return err_requests("500", "档案：%s不存在" % archive_id)
        
        archive = ArchivesFile.objects.get(id=body.get('archive_id'))
        if archive.file_status != '在库':
            return err_requests(
                "500",
                "档案：%s不在档案库中，其状态为：%s"
                % (archive_id, archive.file_status)
            )
        borrow.archive = ArchivesFile.objects.get(id=body.get('archive_id'))
        
        try:
            operator_id = int(body.get('operator_id'))
        except Exception as e:
            traceback.print_exc()
            return err_requests(
                "500", "操作者：%s格式错误" % body.get('operator_id')
            )
        
        operator_query = CloudAuthUser.objects.filter(id=operator_id)
        if not operator_query:
            return err_requests("500", "操作者：%s不存在" % operator_id)
        
        borrow.operator = CloudAuthUser.objects.get(id=operator_id)
        deadline_str = body.get("return_deadline").__str__()
        try:
            deadline = datetime.datetime.strptime(deadline_str, '%Y-%m-%d')
        except Exception as e:
            traceback.print_exc()
            return err_requests("500", "计划归还日期：%s格式错误" % deadline_str)
        
        if deadline.date() < datetime.datetime.now().date():
            return err_requests(
                "500", "计划归还日期不能早于借出日期：%s"
                       % datetime.datetime.now().date().strftime('%Y-%m-%d')
            )
        borrow.return_deadline = deadline
        
        if not body.get("borrower"):
            return err_requests("500", "借阅人不能为空")
        
        borrow.borrower = body.get("borrower")
        borrow.borrow_time = datetime.datetime.now()
        borrow.status = "借阅"
        borrow.save()
        archive_query.update(borrowing_record=borrow, file_status='借出')
        return success_requests()
    except Exception as e:
        print e
        return err_requests("500")


def oper_return(request):
    """
    归还资料
    """
    cursor = connection.cursor()
    try:
        check_delay()
        if request.method != 'GET':
            return err_requests("500", "请求方法错误，请用GET请求")
        args = request.GET
        try:
            borrow_id = int(args.get("id"))
        except Exception as e:
            traceback.print_exc()
            return err_requests("500", "借阅记录id：%s格式错误" % args.get('id'))
        
        borrow_query = BorrowRecord.objects.filter(id=borrow_id)
        if not borrow_query:
            return err_requests("500", "该条借阅记录：%s不存在" % borrow_id)
        
        borrow = BorrowRecord.objects.get(id=borrow_id)
        if borrow.return_time:
            return err_requests("500", "本次借阅已经完成归还，请勿重复记录")
        
        try:
            operator_id = int(args.get('operator_id'))
        except Exception as e:
            traceback.print_exc()
            return err_requests(
                "500", "操作者：%s格式错误" % args.get('operator_id')
            )
        
        operator_query = CloudAuthUser.objects.filter(id=operator_id)
        if not operator_query:
            return err_requests("500", "操作者：%s不存在" % operator_id)
        
        return_sql = borrow_sql.RETURN_ARCHIVES
        cursor.execute(return_sql, (operator_id, borrow_id))
        return success_requests()
    except Exception as e:
        print(e)
        return err_requests("500")


def query_borrow_all(request):
    cursor = connection.cursor()
    try:
        check_delay()
        if sys.getdefaultencoding() != 'utf-8':
            reload(sys)
            sys.setdefaultencoding('utf-8')
            defaultencoding = sys.getdefaultencoding()
        request.encoding = 'utf-8'
        if request.method != "POST":
            return err_requests("500", "请求方法错误，请使用POST请求")
        
        body = request.POST
        keyword = body.get('query').encode('utf-8') \
            if body.get('query') else ''
        keyword = keyword.__str__() if keyword else ''
        
        try:
            borrow_id = int(body.get('id'))
        except:
            borrow_id = 0
        
        try:
            page = int(body.get('page'))
        except Exception as e:
            traceback.print_exc()
            return err_requests("500", "页码：%s格式错误" % body.get('page'))
        
        if page < 1:
            return err_requests("500", "页码必须为大于0的整数")
        
        try:
            size = int(body.get('size'))
        except Exception as e:
            traceback.print_exc()
            return err_requests("500", "单页数据量：%s格式错误" % body.get('size'))
        
        if size < 1:
            return err_requests("500", "单页数据量必须为大于0的整数")
        
        count_sql = borrow_sql.SELECT_BORROW_RECORDS_COUNT
        select_sql = borrow_sql.SELECT_BORROW_RECORDS
        content = ''
        
        if keyword:
            content += " AND af.serial LIKE '%%%s%%'" \
                       " OR af.title LIKE '%%%s%%'" % (keyword, keyword)
        
        if borrow_id:
            content += " AND bc.id = %s" % borrow_id
        
        cursor.execute(count_sql + content)
        borrow_count = cursor.fetchone()[0]
        total_page = borrow_count / size \
            if not borrow_count % size else borrow_count / size + 1
        
        content += " LIMIT %s, %s" % ((page - 1) * size, size)
        cursor.execute(select_sql + content)
        columns = [col[0] for col in cursor.description]
        data = [
            dict(zip(columns, row))
            for row in cursor.fetchall()
        ]
        ret = dict({
            "page": page,
            "size": size,
            "totalPage": total_page,
            "totalSize": borrow_count,
            "data": data
        })
        return success_requests(ret)
    except Exception as e:
        traceback.print_exc()
        return err_requests("500")


def query_return_all(request):
    cursor = connection.cursor()
    try:
        check_delay()
        if sys.getdefaultencoding() != 'utf-8':
            reload(sys)
            sys.setdefaultencoding('utf-8')
            defaultencoding = sys.getdefaultencoding()
        request.encoding = 'utf-8'
        if request.method != "POST":
            return err_requests("500", "请求方法错误，请使用POST请求")
        
        body = request.POST
        keyword = body.get('query').encode('utf-8') \
            if body.get('query') else ''
        keyword = keyword.__str__() if keyword else ''
        
        try:
            borrow_id = int(body.get('id'))
        except:
            borrow_id = 0
        
        try:
            page = int(body.get('page'))
        except Exception as e:
            traceback.print_exc()
            return err_requests("500", "页码：%s格式错误" % body.get('page'))
        
        if page < 1:
            return err_requests("500", "页码必须为大于0的整数")
        
        try:
            size = int(body.get('size'))
        except Exception as e:
            traceback.print_exc()
            return err_requests("500", "单页数据量：%s格式错误" % body.get('size'))
        
        if size < 1:
            return err_requests("500", "单页数据量必须为大于0的整数")
        
        count_sql = borrow_sql.SELECT_RETURN_RECORDS_COUNT
        select_sql = borrow_sql.SELECT_RETURN_RECORDS
        content = ''
        
        if keyword:
            content += " AND (af.serial LIKE '%%%s%%'" \
                       " OR af.title LIKE '%%%s%%')" % (keyword, keyword)
        
        if borrow_id:
            content += " AND bc.id = %s" % borrow_id
        
        print 'sql: %s' % count_sql + content
        cursor.execute(count_sql + content)
        borrow_count = cursor.fetchone()[0]
        total_page = borrow_count / size \
            if not borrow_count % size else borrow_count / size + 1
        
        content += " LIMIT %s, %s" % ((page - 1) * size, size)
        cursor.execute(select_sql + content)
        columns = [col[0] for col in cursor.description]
        data = [
            dict(zip(columns, row))
            for row in cursor.fetchall()
        ]
        ret = dict({
            "page": page,
            "size": size,
            "totalPage": total_page,
            "totalSize": borrow_count,
            "data": data
        })
        return success_requests(ret)
    except Exception as e:
        traceback.print_exc()
        return err_requests("500")


def check_delay():
    cursor = connection.cursor()
    try:
        check_sql = borrow_sql.DELAY_CHACK
        cursor.execute(check_sql)
    except Exception as e:
        traceback.print_exc()
